package com.foodapp.back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.foodapp.back.dto.RestaurantDTO;
import com.foodapp.back.entity.Restaurant;
import com.foodapp.back.exception.ApiException;
import com.foodapp.back.mapper.RestaurantMapper;
import com.foodapp.back.service.RestaurantService;
import com.foodapp.back.vo.RestaurantVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 餐厅服务实现类
 */
@Service
public class RestaurantServiceImpl extends ServiceImpl<RestaurantMapper, Restaurant> implements RestaurantService {

    @Override
    public Page<RestaurantVO> pageList(Integer page, Integer size, String category, String keyword) {
        Page<Restaurant> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<Restaurant> wrapper = new LambdaQueryWrapper<>();
        
        // 查询条件
        wrapper.eq(Restaurant::getStatus, 1); // 只查询营业中的餐厅
        
        if (StringUtils.isNotBlank(category)) {
            wrapper.eq(Restaurant::getCategory, category);
        }
        
        if (StringUtils.isNotBlank(keyword)) {
            wrapper.like(Restaurant::getName, keyword)
                    .or().like(Restaurant::getDescription, keyword);
        }
        
        // 按评分和月销量降序排序
        wrapper.orderByDesc(Restaurant::getRating, Restaurant::getMonthlySales);
        
        // 查询分页数据
        Page<Restaurant> restaurantPage = page(pageParam, wrapper);
        
        // 转换为VO
        Page<RestaurantVO> result = new Page<>();
        BeanUtils.copyProperties(restaurantPage, result, "records");
        
        List<RestaurantVO> restaurantVOList = restaurantPage.getRecords().stream().map(restaurant -> {
            RestaurantVO restaurantVO = new RestaurantVO();
            BeanUtils.copyProperties(restaurant, restaurantVO);
            return restaurantVO;
        }).collect(Collectors.toList());
        
        result.setRecords(restaurantVOList);
        
        return result;
    }

    @Override
    public RestaurantVO getRestaurantById(Long id) {
        Restaurant restaurant = getById(id);
        if (restaurant == null) {
            throw new ApiException("餐厅不存在");
        }
        
        RestaurantVO restaurantVO = new RestaurantVO();
        BeanUtils.copyProperties(restaurant, restaurantVO);
        return restaurantVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addRestaurant(RestaurantDTO restaurantDTO) {
        // 校验数据
        validateRestaurantData(restaurantDTO);
        
        // 创建餐厅实体
        Restaurant restaurant = new Restaurant();
        BeanUtils.copyProperties(restaurantDTO, restaurant);
        
        // 设置初始值
        restaurant.setMonthlySales(0);
        restaurant.setRating(BigDecimal.valueOf(5.0)); // 初始评分为5
        restaurant.setStatus(restaurantDTO.getStatus() != null ? restaurantDTO.getStatus() : 1);
        restaurant.setIsDeleted(0);
        
        return save(restaurant);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateRestaurant(RestaurantDTO restaurantDTO) {
        // 校验餐厅是否存在
        Restaurant restaurant = getById(restaurantDTO.getId());
        if (restaurant == null) {
            throw new ApiException("餐厅不存在");
        }
        
        // 校验数据
        validateRestaurantData(restaurantDTO);
        
        // 更新餐厅信息
        BeanUtils.copyProperties(restaurantDTO, restaurant);
        
        return updateById(restaurant);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteRestaurant(Long id) {
        // 校验餐厅是否存在
        Restaurant restaurant = getById(id);
        if (restaurant == null) {
            throw new ApiException("餐厅不存在");
        }
        
        // 逻辑删除
        return removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatus(Long id, Integer status) {
        // 校验餐厅是否存在
        Restaurant restaurant = getById(id);
        if (restaurant == null) {
            throw new ApiException("餐厅不存在");
        }
        
        // 更新状态
        restaurant.setStatus(status);
        
        return updateById(restaurant);
    }
    
    /**
     * 校验餐厅数据
     */
    private void validateRestaurantData(RestaurantDTO restaurantDTO) {
        if (restaurantDTO.getDeliveryFee().compareTo(BigDecimal.ZERO) < 0) {
            throw new ApiException("配送费不能为负数");
        }
        
        if (restaurantDTO.getMinOrderAmount().compareTo(BigDecimal.ZERO) < 0) {
            throw new ApiException("起送价格不能为负数");
        }
    }
}
